package com.qf.dao;

import com.qf.pojo.Cart;
import com.qf.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author hanjiejie
 * @version V1.0
 * @Project java2203
 * @Package com.qf.dao
 * @Description:
 * @Date 2022/5/26 14:57
 */
public class CartDaoImpl implements CartDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDateSource());

    /**
     * 根据 用户id和商品id去数据库里查询是否有该购物项
     * @param uid
     * @param pid
     * @return
     */
    @Override
    public Cart findCartByUidAndpid(Integer uid, Integer pid) {
      String sql ="SELECT *FROM tb_cart WHERE uid=? and pid=?";
        try {
            Cart cart = queryRunner.query(sql, new BeanHandler<Cart>(Cart.class), uid, pid);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新购物车里的数据
     * @param cart
     */
    @Override
    public void updateCart(Cart cart) {
        String sql ="update tb_cart set num=?, money=? where cid=? ";
        try {
            queryRunner.update(sql, cart.getNum(),cart.getMoney(),cart.getCid());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加商品到购物车
     * @param cart
     */
    @Override
    public void insertCart(Cart cart) {
        String sql ="insert into tb_cart values(null,?,?,?,?)";
        try {
            queryRunner.update(sql,cart.getUid(),cart.getPid(),cart.getNum(),cart.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Cart> findCartByUid(Integer id) {
        String sql="select *from tb_cart where uid=?";
        try {
            List<Cart> list = queryRunner.query(sql, new BeanListHandler<Cart>(Cart.class), id);
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
